package com.myopen.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.crypto.hash.Sha256Hash;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.myopen.config.ConstConfig;
import com.myopen.converter.ListConverter;

import com.myopen.kit.UUIDKit;

public class User extends Model<User>{

	private static final long serialVersionUID = -7975549526181956964L;
	public static final User dao = new User();
	
	//注入user,这个user是从拦截器里面组装的
	public static boolean hasAuthUrl(String url,Record currUser){
		Map<String,Record> sessionResourceUrls=currUser.get(ConstConfig.SESSION_ADMIN_RESOURCE_URLS);
		if(sessionResourceUrls.get(Resource.formatUrl(url))!=null){
			return true;
		}
		return false;
	}
	
	public static boolean hasAuthCode(String code,Record currUser){
		Map<String,Record> sessionResourceCodes=currUser.get(ConstConfig.SESSION_ADMIN_RESOURCE_CODES);
		if(sessionResourceCodes.get(code)!=null){
			return true;
		}
		return false;
	}
	
	public static boolean hasAuthRole(String roleCode,Record currUser){
		Record role=currUser.get(ConstConfig.SESSION_ADMIN_ROLE);
		if(roleCode.equals(role.getStr("code"))){
			return true;
		}
		return false;
	}
	
	public static String encryptPassword(String password,String salt){
		if(StrKit.isBlank(salt)){
			return null;
		}
		//password为密码，salt为用户盐值，2为hash次数
		return new Sha256Hash(password, salt, 2).toString();
	}
	
	public Record getRecordByUsername(String username){
		String sql="select * from t_user t where t.username=? ";
		return Db.findFirst(sql,username);
	}
	
	public Record getRecordByEmail(String email){
		String sql="select * from t_user t where t.email=? ";
		return Db.findFirst(sql,email);
	}
	
	public Record getRecordByCellphone(String cellphone){
		String sql="select * from t_user t where t.cellphone=? ";
		return Db.findFirst(sql,cellphone);
	}
	
	public Page<Record> pagequery(Record record){
		StringBuffer sqlExceptSelect=new StringBuffer("from t_user t "
				+ " left join t_role r on t.roleId=r.id "
				+ " where t.removed='0' ");
		List<Object> list=new ArrayList<Object>();
		
		if(StrKit.notBlank(record.getStr("username"))){
			sqlExceptSelect.append(" and t.username like ? ");
			list.add("%"+record.getStr("username")+"%");
		}
		if(StrKit.notBlank(record.getStr("nickname"))){
			sqlExceptSelect.append(" and t.nickname like ? ");
			list.add("%"+record.getStr("nickname")+"%");
		}
		if(StrKit.notBlank(record.getStr("email"))){
			sqlExceptSelect.append(" and t.email like ? ");
			list.add("%"+record.getStr("email")+"%");
		}
		if(StrKit.notBlank(record.getStr("cellphone"))){
			sqlExceptSelect.append(" and t.cellphone like ? ");
			list.add("%"+record.getStr("cellphone")+"%");
		}
		if(StrKit.notBlank(record.getStr("searchContent"))){
			sqlExceptSelect.append(" and (t.username like ? or t.nickname like ? or t.email like ? or t.cellphone like ?) ");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
			list.add("%"+record.getStr("searchContent")+"%");
		}
		if(StrKit.notBlank(record.getStr("status"))){
			sqlExceptSelect.append(" and t.status = ? ");
			list.add(record.getStr("status"));
		}
		if(StrKit.notBlank(record.getStr("memberCodeIn"))){
			sqlExceptSelect.append(" and r.code in (?) ");
			list.add(record.getStr("memberCodeIn"));
		}
		
		sqlExceptSelect.append(" order by t.createTime desc");
		Page<Record> page= Db.paginate(record.getInt("pageNumber"),record.getInt("pageSize"),"select t.*,r.name roleName ",sqlExceptSelect.toString(),list.toArray());		
		String[] dicTypeKeys= {"status"};
		String[] dicTypes= {"USER_STATUS"};
		
		return new ListConverter<Record>(page,dicTypeKeys,dicTypes).getPage();
	}
	
	public Record getRecordById(String id){
		if(StrKit.isBlank(id)){
			return new Record();
		}
		String sql="select * from t_user t where t.id=? ";
		return Db.findFirst(sql,id);
	}
	
	public User save(User vo,Record currUser){
		User bo=null;
		if(StrKit.isBlank(vo.getStr("id"))){
			bo=new User();
			
			String salt=UUIDKit.getUUID();
			
			bo.set("id", UUIDKit.getUUID());
			bo.set("removed", "0");
			bo.set("username", vo.getStr("username"));
			bo.set("createTime", new Date());
			bo.set("updateTime", new Date());
			bo.set("creator", currUser.getStr("id"));
			bo.set("updator", currUser.getStr("id"));
			bo.set("nickname", vo.getStr("nickname"));
			bo.set("cellphone", vo.getStr("cellphone"));
			bo.set("email", vo.getStr("email"));
			bo.set("password", User.encryptPassword(vo.getStr("password"), salt));
			bo.set("salt", salt);
			bo.set("roleId", vo.getStr("roleId"));
			bo.set("isCellphoneVerify", "1");
			bo.set("isEmailVerify", "1");
			bo.set("status", "USER_STATUS_01");//默认可用
			bo.set("comment", vo.getStr("comment"));
			
			bo.save();
		}else{
			bo=User.dao.findById(vo.getStr("id"));
			
			bo.set("updateTime", new Date());
			bo.set("updator", currUser.getStr("id"));
			bo.set("username", vo.getStr("username"));
			bo.set("nickname", vo.getStr("nickname"));
			bo.set("cellphone", vo.getStr("cellphone"));
			bo.set("email", vo.getStr("email"));
			bo.set("roleId", vo.getStr("roleId"));
			bo.set("comment", vo.getStr("comment"));

			bo.update();
		}
		
		return bo;
	}
	
	public void changeStatus(String id,String status,Record currUser){
		User bo=User.dao.findById(id);
		bo.set("updateTime", new Date());
		bo.set("updator", currUser.getStr("id"));
		bo.set("status", status);
		bo.update();
	}
	
	public User remove(String id,Record currUser) {
		User bo=User.dao.findById(id);
		bo.set("removed", "1");
		bo.set("updateTime", new Date());
		bo.set("updator", currUser.getStr("id"));
		bo.update();
		return bo;
	}
	
}
